/*
 *   Copyright (C) 2008 - 2009  FireBalls
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// includes
#include "Highscore.h"

Highscore::Highscore() {
    for(int i = 0; i < 10; i++) {
        points[i] = 0;
        name[i] = "";
    }
}

void Highscore::getScore() {

    for(int i = 0; i < 10; i++) {
        string str;
        ostringstream stream;

        stream << "player" << i + 1 << "points";
        str = stream.str();


        points[i] = getInt(str, 10);

    }

    for(int i = 0; i < 10; i++) {
        string str;
        ostringstream stream;

        stream << "player" << i + 1 << "name";
        str = stream.str();


        name[i] = getString(str, "");

    }


}

int Highscore::getPoints(int i) {
    if(i < 0 || i > 9) {
        return -1;
    }
    getScore();
    return points[i];
}

string Highscore::getName(int i) {
    getScore();
    return name[i];
}

int Highscore::New(string str, int i) {

    getScore();

    for(int k = 0; k < 10; k++) {
        if(points[k] < i) {
            Sort(k);

            points[k] = i;

            name[k] = str;

            Save();

            return 1;
        }
    }
    return 0;
}

void Highscore::Sort(int i) {

    for(int j = 9; j > i; j--) {
        points[j] = points[j - 1];
        name[j] = name[j - 1];
    }
}

void Highscore::Save() {
    fstream file;

    file.open(path.c_str(), ios::out);

    for(int i = 0; i < 10; i++) {

        file << "player" << i + 1 << "name = " << name[i] << endl;
        file << "player" << i + 1 << "points = " << points[i] << endl;

    }

    file.close();
}
